package com.bsoft.mvpmy.ui.home;

import android.annotation.TargetApi;
import android.app.Fragment;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bsoft.mvpmy.R;
import com.bsoft.mvpmy.widget.LoadingView;


/**
 * User: LWD
 * Date: 2016/11/29
 * Email: 13102169005@163.com
 * Description:
 */

public class FirstFragment extends Fragment implements View.OnClickListener{

    private WebView wb_first;
    private String url;
    private boolean isMainError;
    private LinearLayout errorLayout;
    private TextView errorMessage;
    private Button errorReloadButton;
    private LoadingView wd_loding;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:
                    webViewGoBack();
                    break;
            }
        }
    };
    private void webViewGoBack() {
        wb_first.goBack();
    }
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        url = this.getArguments().getString("url");

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragemnt_first, null);
        findId(v);
        initErrorLayout();
        initWebView();//初始化WebView
        initWebSettings();//初始化WebSettings
        initWebViewClient();//初始化WebViewClient
        initWebChromeClient();//初始化WebChromeClient
        initView(); //初始化
        return v;
    }

    private void initView() {
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

    }

    /**
     * 找组件
     */
    private void findId(View v) {
        wb_first = (WebView)v.findViewById(R.id.wb_first);
        wd_loding = (LoadingView) v.findViewById(R.id.wd_loding);
        errorLayout = (LinearLayout) v.findViewById(R.id.error_layout);
        errorMessage = (TextView) v.findViewById(R.id.error_message_text);
        errorReloadButton = (Button) v.findViewById(R.id.error_reload_btn);
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.wb_first:

                break;
        }
    }

    @Override
    public void onDestroyView() {
        if (wb_first != null) {
            wb_first.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            wb_first.clearHistory();
            ((ViewGroup) wb_first.getParent()).removeView(wb_first);
            wb_first.destroy();
            wb_first = null;
        }
        super.onDestroyView();
    }

    
    private void initWebView() {
        wb_first.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);//取消滚动条
        wb_first.requestFocus();//触摸焦点起作用
        wb_first.requestFocusFromTouch();//支持获取手势焦点
        initWebSettings();//初始化WebSettings
                if (!TextUtils.isEmpty(url)){
            wb_first.loadUrl(url);

        }else {
            wb_first.loadUrl("http://www.baidu.com/");

        }
    }

    private void initWebSettings() {
        WebSettings settings = wb_first.getSettings();
        //设置编码格式
        settings.setDefaultTextEncodingName("UTF-8");
        //支持JS
        settings.setJavaScriptEnabled(true);
        //设置适应屏幕
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        //支持缩放
        settings.setSupportZoom(false);
        //隐藏原生的缩放控件
        settings.setDisplayZoomControls(false);
        //支持内容重新布局
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.supportMultipleWindows();
        settings.setSupportMultipleWindows(false);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        //设置缓存模式、
        settings.setCacheMode(WebSettings.LOAD_DEFAULT);
        settings.setDomStorageEnabled(true);
        settings.setDatabaseEnabled(true);
        settings.setAppCacheEnabled(true);
        settings.setAppCachePath(wb_first.getContext().getCacheDir().getAbsolutePath());
        //设置可访问文件
        settings.setAllowFileAccess(false);
        //当webview调用requestFocus时为webview设置节点
        settings.setNeedInitialFocus(true);
        //支持自动加载图片
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            settings.setLoadsImagesAutomatically(true);
        } else {
            settings.setLoadsImagesAutomatically(false);
        }
        wb_first.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int i, KeyEvent keyEvent) {
                if((i==KeyEvent.KEYCODE_BACK)&&wb_first.canGoBack()){
                    handler.sendEmptyMessage(1);
                    return true;
                }
                return false;
            }
        });

    }

    private void initWebViewClient() {
        wb_first.setWebViewClient(new WebViewClient() {

            //页面开始加载时
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                wd_loding.setVisibility(View.VISIBLE);

                wd_loding.startLoading(200);
                super.onPageStarted(view, url, favicon);

            }

            //页面完成加载时
            @Override
            public void onPageFinished(WebView view, String url) {
                if (!isMainError) {
                    wb_first.setVisibility(View.VISIBLE);
                    wd_loding.stopLoading();
                    wd_loding.setVisibility(View.INVISIBLE);
                }
                super.onPageFinished(view, url);
            }

            //是否在WebView内加载新页面
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                view.loadUrl(request.toString());
                return true;
            }

            //网络错误时回调的方法
            @TargetApi(Build.VERSION_CODES.M)
            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                //如果错误由主体引起，则显示错误页面
                if (request.isForMainFrame()) {
                    isMainError = true;
                    errorMessage.setText(error.getDescription().toString());
                    errorLayout.setVisibility(View.VISIBLE);
                    wb_first.setVisibility(View.INVISIBLE);
                    wd_loding.stopLoading();
                    wd_loding.setVisibility(View.INVISIBLE);
                }
                super.onReceivedError(view, request, error);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    return;
                }
                //显示错误页面
                isMainError = true;
                errorMessage.setText(description);
                errorLayout.setVisibility(View.VISIBLE);
                wb_first.setVisibility(View.INVISIBLE);
                super.onReceivedError(view, errorCode, description, failingUrl);
            }

            @TargetApi(Build.VERSION_CODES.M)
            @Override
            public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
                wd_loding.stopLoading();
                wd_loding.setVisibility(View.INVISIBLE);
                super.onReceivedHttpError(view, request, errorResponse);
            }

        });
    }

    private void initWebChromeClient() {

        wb_first.setWebChromeClient(new WebChromeClient() {

            //=========多窗口===========
            @Override
            public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
                WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
                transport.setWebView(view);
                resultMsg.sendToTarget();
                return true;
            }

        });
    }

    private void initErrorLayout() {
        errorReloadButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                isMainError = false;
                wb_first.reload();
                errorMessage.setText("");
                errorLayout.setVisibility(View.GONE);
            }

        });
    }

}
